package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LeetCode15 {

    public static void main(String[] args) {
        LeetCode15 leetCode15 = new LeetCode15();
        //-2 -1 0 1 2 3
        System.out.println(leetCode15.threeSum(new int[]{3, 0, -2, -1, 1, 2}));
    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        int lastNum = Integer.MAX_VALUE, lastLeft = Integer.MAX_VALUE, lastRight = Integer.MIN_VALUE, left, right, sum;
        for (int i = 0; i <= nums.length - 2; i++) {
            left = i + 1;
            right = nums.length - 1;
            if (nums[i] > 0 || nums[i] == lastNum)
                break;
            while (left < right) {
                System.out.println(i + " " + left + " " + right);
                sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {

                    List<Integer> tmpList = result.get(i);
                    if (result.size() == 0 || (tmpList.get(0) == nums[i] && tmpList.get(1) == nums[left] && tmpList.get(2) == nums[right])) {
                        List<Integer> list = new ArrayList<>();
                        Collections.addAll(list, nums[i], nums[left], nums[right]);
                        result.add(list);
                    }
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
            lastNum = nums[i];
        }
        return result;
    }

    //------------------------------------------------------------------
    public static List<List<Integer>> threeSum1(int[] nums) {
        List<List<Integer>> ans = new ArrayList();
        int len = nums.length;
        if (nums == null || len < 3) return ans;
        Arrays.sort(nums); // 排序
        for (int i = 0; i < len; i++) {
            if (nums[i] > 0) break; // 如果当前数字大于0，则三数之和一定大于0，所以结束循环
            if (i > 0 && nums[i] == nums[i - 1]) continue; // 去重
            int L = i + 1;
            int R = len - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    ans.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    while (L < R && nums[L] == nums[L + 1]) L++; // 去重
                    while (L < R && nums[R] == nums[R - 1]) R--; // 去重
                    L++;
                    R--;
                } else if (sum < 0) L++;
                else if (sum > 0) R--;
            }
        }
        return ans;
    }
}
